<template>
    <div class="content-wrapper" v-loading.fullscreen.lock="fullscreenLoading">
        <el-row class="content-row">
            <el-form ref="addForm" :model="addForm" :rules="addRules" label-width="140px">
                <el-row>
                    <el-col :span="15">

                        <el-form-item label="商品名称" prop="goodsName">
                            <span >{{addForm.goodsName}}</span>
                        </el-form-item>

                        <el-form-item label="商品最小售卖单位" prop="minNum">

                            <span >{{addForm.minNum}}</span>

                        </el-form-item>

                        <el-form-item label="规格数量" prop="goodsSpecNum">

                            <span >{{addForm.goodsSpecNum}}</span>
                        </el-form-item>
                        <el-form-item label="规格单位" prop="goodsSpecUnit">

                            <span >{{addForm.goodsSpecUnit}}</span>
                        </el-form-item>

                        <el-form-item label="库存数量" prop="inventoryNum">

                            <span >{{addForm.inventoryNum}}</span>
                        </el-form-item>

                        <el-form-item label="消耗积分" prop="integralNum">

                            <span >{{addForm.integralNum}}</span>
                        </el-form-item>

                        <el-form-item label="市面价格" prop="marketPrice">
                            <span >{{addForm.marketPrice}}</span>
                        </el-form-item>

                        <el-form-item label="客服电话" prop="serviceTel">
                            <span >{{addForm.serviceTel}}</span>
                        </el-form-item>
                        <el-form-item label="商品头图" prop="headImg">
                            <span>
                                <img :src="addForm.headImg"  class="image" width="160px" height="163px" />
                            </span>
                        </el-form-item>

                        <el-form-item label="商品页轮播图" prop="carouselImg">
                            <div v-for="item in carouselPicList">
                                <img :src="item.url"  class="image" width="375px" height="168px"/>
                            </div>
<!--                            <span>请上传小于200KB，宽高：690*288像素</span>-->

                        </el-form-item>
                        <el-form-item label="商品页详情图" prop="detailsImg">
                            <div v-for="item in detailPicList">
                                <img :src="item.url"  class="image" width="375px" />
                            </div>


                        </el-form-item>


                        <el-form-item label="兑换说明" prop="activityIntroduce">

                            <span >{{addForm.description}}</span>

                        </el-form-item>
                    </el-col>
                </el-row>


            </el-form>
        </el-row>

        <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="closeTab">取 消</el-button>
            <el-button type="primary" @click="saveForm('addForm',0)">保存</el-button>
            <el-button type="primary" @click="saveForm('addForm',1)">发布</el-button>
        </div>

        <!--        <subBannerDeatil v-if='openDialog' v-on:handleclose='subBannerDone' v-bind:editData='editRow' v-bind:index='editIndex'/>-->
    </div>
</template>

<script>

    // import CityTree from './CityTree'
    // import titleTip from '../../../common/titleTip.vue'
    import {edit, getMallGoodsDetailsById} from '../../../../api/mall/goodsDetail'


    export default {
        name: 'goodsDetailEdit',

        data() {
            var checkActivityTime = (rule, value, callback) => {
                let applyTime = this.addForm.applyTime;
                let activityTime = value;

                if (applyTime.length > 0 && activityTime.length > 0) {

                    let activityBeginTime = activityTime[0].getTime();
                    let activityEndTime = activityTime[1].getTime();

                    let applyBeginTime = applyTime[0].getTime();
                    let applyEndTime = applyTime[1].getTime();

                    console.log(activityBeginTime, activityEndTime, applyBeginTime, applyEndTime)

                    if (activityEndTime < applyEndTime) {
                        return callback(new Error("活动结束时间不得早于报名结束时间"));
                    } else if (activityBeginTime < applyBeginTime) {
                        return callback(new Error("报名开始时间不得迟于活动开始时间"));
                    } else {
                        callback();
                    }
                } else {
                    callback();
                }

            };
            var checkApplyTime = (rule, value, callback) => {
                let applyTime = value;
                let activityTime = this.addForm.time;
                if (applyTime.length > 0 && activityTime.length > 0) {

                    let activityBeginTime = activityTime[0].getTime();
                    let activityEndTime = activityTime[1].getTime();

                    let applyBeginTime = applyTime[0].getTime();
                    let applyEndTime = applyTime[1].getTime();

                    console.log(activityBeginTime, activityEndTime, applyBeginTime, applyEndTime)


                    if (activityEndTime < applyEndTime) {
                        return callback(new Error("活动结束时间不得早于报名结束时间"));
                    } else if (activityBeginTime < applyBeginTime) {
                        return callback(new Error("报名开始时间不得迟于活动开始时间"));
                    } else {
                        callback();
                    }
                } else {
                    callback();
                }

            };
            return {

                isAdvertise: true,//广告图片
                isOnline: false,//线上活动
                isOffline: false,//线下活动

                externalData: [],
                tableData: [],
                picList: [],
                detailPicList: [],
                carouselPicList: [],

                editIndex: '',
                editRow: {},
                spaces: [],
                uploadImgNum: 0,
                uploadDetailImgNum: 0,
                uploadAdvertiseImgNum: 0,

                dialogImageUrlImg: '',
                dialogVisibleImg: false,


                limit: 1,
                advertiseLimit: 5,

                detailsPiclimit:5,

                openDialog: false,
                viewdialog: false,
                fullscreenLoading: false,

                apply: true,

                detailsImg: [],
                carouselImgList: [],
                uploadUrl: 'https://lht.ah-zk.com/qjt/fs/file/upload',
                origin: 'https://lht.ah-zk.com/qjt/fs/origin',
                imageStyle: [
                    // {
                    //     code: "1",
                    //     name: "单图",
                    //     url: require("../../../../assets/img/01.png")
                    // }, {
                    //     code: "2",
                    //     name: "双图",
                    //     url: require("../../../../assets/img/02.png")
                    // }, {
                    //     code: "3",
                    //     name: "三图",
                    //     url: require("../../../../assets/img/03.png")
                    // }, {
                    //     code: "4",
                    //     name: "四图",
                    //     url: require("../../../../assets/img/04.png")
                    // }
                ],
                addForm: {
                    goodsName: '',
                    goodsSpecNum: '',
                    goodsSpecUnit: '',
                    minNum: '',
                    inventoryNum: '',
                    integralNum: '',
                    marketPrice: '',
                    serviceTel: '',
                    headImg: '',
                    carouselImg: '',
                    detailsImg: '',
                    description: '',
                    goodsSpecNum: '',
                    goodsSpecUnit: '',
                    status:''

                },
                addRules: {
                    goodsName: [
                        {required: true, message: '请输入商品名称', trigger: ['blur', 'change']}
                    ],
                    goodsSpecNum: [
                        {required: true, message: '请输入规格数量', trigger: ['blur', 'change']}
                    ],
                    goodsSpecUnit: [
                        {required: true, message: '请输入规格单位', trigger: ['blur', 'change']}
                    ],
                    minNum: [
                        {required: true, message: '请输入最小售卖单位', trigger: ['blur', 'change']}
                    ],
                    goodsSpecNum: [
                        {required: true, message: '请输入规格数量', trigger: ['blur', 'change']}
                    ],
                    goodsSpecUnit: [
                        {required: true, message: '请输入规格单位', trigger: ['blur', 'change']}
                    ],
                    inventoryNum: [
                        {required: true, message: '请输入库存数量', trigger: ['blur', 'change']}
                    ],
                    integralNum: [
                        {required: true, message: '请输入兑换积分', trigger: ['blur', 'change']}
                    ],
                    marketPrice: [
                        {required: true, message: '请输入市面价格', trigger: ['blur', 'change']}
                    ],
                    serviceTel: [
                        {required: true, message: '请输入客服电话', trigger: ['blur', 'change']}
                    ],
                    headImg: [
                        {required: true, message: '请上传头图', trigger: ['blur', 'change']}
                    ],
                    carouselImg: [
                        {required: true, message: '请上传轮播图片', trigger: ['blur', 'change']}
                    ]
                }
            };
        },
        created() {
            // this.changeStyle();
            // this.getMoreSpace();
            this.loadGoodsDetailInfo();
        },
        components: {
            // subBannerDeatil,
            //CityTree,
            //titleTip
        },
        methods: {
            loadGoodsDetailInfo() {
                let self = this;
                let path = this.$route.fullPath.split("/");
                console.log(path[path.length - 1]);

                let id = path[path.length - 1];

                console.log(id);
                getMallGoodsDetailsById(id).then(res => {
                    this.addForm.id = id;
                    this.addForm = res.data
                    let data = res.data;
                    this.addForm.headImg = this.origin + "/" + data.headImg;
                    self.picList = [];
                    if (data.headImg != null) {
                        let json = {
                            name: 'aa',
                            url: this.origin + "/" + data.headImg
                        }
                        self.picList.push(json);
                        self.uploadImgNum++;
                    }

                    self.carouselPicList = [];
                    this.carouselImgList = [];
                    if(data.carouselImg != null){
                        let imgs = data.carouselImg.split(",");
                        console.log(imgs);
                        for (let i = 0 ; i< imgs.length;i++){
                            let json ={
                                name:'aa',
                                url:this.origin+"/"+imgs[i]
                            }
                            self.carouselPicList.push(json);
                            self.uploadAdvertiseImgNum++;
                            this.carouselImgList.push(imgs[i]);
                        }
                    }

                    self.detailPicList = [];
                    this.detailsImg = [];
                    if(data.detailsImg != null){
                        let imgs = data.detailsImg.split(",");
                        console.log(imgs);
                        for (let i = 0 ; i< imgs.length;i++){
                            let json ={
                                name:'aa',
                                url:this.origin+"/"+imgs[i]
                            }
                            self.detailPicList.push(json);
                            self.uploadDetailImgNum++;
                            this.detailsImg.push(imgs[i]);
                        }
                    }

                })

            }
            , onAddExternalRow() {
                let external = {
                    name: '',
                    type: 2,
                    placeholder: '',
                    required: true
                }
                this.externalData.push(external)
            },
            //关闭tab
            closeTab() {
                this.closeTagByName('activityAdd');
            },
            //跳转到选择项目弹出框
            viewCity() {
                this.viewdialog = true;
            },
            //选择项目后的回调
            viewinf(e) {
                this.viewdialog = false;
                this.addForm.cityList = e;
                let cityNames = "";
                if (e.length != 0) {
                    for (let i = 0; i < e.length; i++) {
                        if (i != 0) {
                            cityNames += ",";
                        }
                        cityNames += e[i].cityName;
                    }
                }
                this.addForm.cityName = cityNames;
                this.addForm.scope = '2';
            },

            //图片上传删除图片
            handleRemoveImg(file, fileList) {
                this.uploadImgNum = 0;
                this.addForm.headImg = null;
            },
            //图片放大方法
            handlePictureCardPreviewImg(file) {
                this.dialogImageUrlImg = file.url;
                this.dialogVisibleImg = true;
            },
            //图片上传成功回调
            successUploadImg(response, file, fileList) {
                let f = response.files[0];
                this.addForm.headImg = f.fingerprint;
                this.uploadImgNum = 1;
            },

            //图片上传删除图片
            handleRemoveDetailImg(file, fileList) {
                var deleteFileName = file.response.files[0].fingerprint;
                for (var i = 0; i < this.detailPicList.length; i++) {
                    var fileName = this.detailPicList[i];
                    if (fileName == deleteFileName) {
                        this.detailPicList.splice(i, 1);
                        break;
                    }
                }
                this.uploadDetailImgNum--;
                this.addForm.activityAdvertiseImg = null;
            },
            //图片放大方法
            // handlePictureCardPreviewDetailImg(file) {
            //     this.dialogImageUrlImg = file.url;
            //     this.dialogVisibleImg = true;
            // },
            //图片上传成功回调
            successUploadDetailImg(response, file, fileList) {
                let f = response.files[0];
                //this.addForm.activityAdvertiseImg = f.fingerprint;
                // this.detailPicList.push()
                this.detailsImg.push(f.fingerprint);
                this.uploadDetailImgNum++;

            },

            //图片上传成功回调
            successUploadAdvertiseImg(response, file, fileList) {
                let f = response.files[0];
                //this.addForm.activityAdvertiseImg = f.fingerprint;
                this.carouselImgList.push(f.fingerprint)
                this.uploadAdvertiseImgNum++;

                console.log(this.carouselImgList);
            },

            //图片上传删除图片
            handleRemoveAdvertiseImg(file, fileList) {
                var deleteFileName = file.response.files[0].fingerprint;
                for (var i = 0; i < this.carouselImgList.length; i++) {
                    var fileName = this.carouselImgList[i];
                    if (fileName == deleteFileName) {
                        this.carouselImgList.splice(i, 1);
                        break;
                    }
                }
                this.uploadAdvertiseImgNum--;
                this.addForm.activityAdvertiseImg = null;

                console.log()
            },
            //文件上传时做文件大小判断
            beforeUpload(file) {
                const isLt2M = file.size / 1024 / 1024 < 2
                if (!isLt2M) {
                    this.$message({
                        message: '上传文件大小不能超过 200KB!',
                        type: 'warning'
                    });
                }
                return isLt2M;
            },
            onDelExternalRow(row, index) {
                this.externalData.splice(index, 1)
            },
            //提交保存
            saveForm(formName, status) {

                this.addForm.carouselImg = this.carouselImgList.join(",")

                this.addForm.detailsImg = this.detailsImg.join(",")
                if(this.addForm.status === 0){
                    this.addForm.status = status;
                }

                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.fullscreenLoading = true;

                        edit(this.addForm).then(res => {
                            if (res.code == '0') {
                                this.fullscreenLoading = false;
                                this.$message({
                                    message: '修改成功',
                                    type: 'success'
                                });
                                this.resetForm('addForm');
                                this.closeTagByName('goodsDetailEdit');
                                this.$router.push('/mall/goodsDetail/list');
                            } else {
                                this.fullscreenLoading = false;
                                this.$message({
                                    message: res.msg,
                                    type: 'error'
                                });
                            }
                        });
                    } else {
                        return false;
                    }
                })

            }
        },
        watch:{
            "$route":function(to,from){
                if(this.$route.fullPath === to.fullPath){
                    this.loadGoodsDetailInfo();
                }
            }
        }
    };
</script>

<style scoped>

    .content-wrapper {
        height: 100%;
        overflow-y: scroll;
    }

    .content-row {
        height: 94%;
        overflow-y: scroll;
    }

    .imageFloatLeft {
        width: 40%;
        float: left;
        height: 140px;
        margin-right: 2%;
    }

    .dialog-footer {
        text-align: center;
    }
</style>
